package com.api.rc.interceptor;

import com.api.base.config.auth.JwtAuthenticationTokenFilter;
import com.api.rc.service.RapidChallengeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author RenQiang
 * @date 2021/7/17
 */
@Slf4j
public class LobbyHandshakeInterceptor implements HandshakeInterceptor {
    public static final String ROOM_ID_KEY = "roomId";
    public static final String PASSWORD_KEY = "password";

    private final RapidChallengeService rapidChallengeService;

    public LobbyHandshakeInterceptor(RapidChallengeService rapidChallengeService) {
        this.rapidChallengeService = rapidChallengeService;
    }

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        String roomIdStr = servletRequest.getParameter(ROOM_ID_KEY);
        if (StringUtils.isEmpty(roomIdStr)) {
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            log.error("快速挑战大厅>>加入大厅失败 => 缺少参数: {}", ROOM_ID_KEY);
            return false;
        }
        Long roomId = Long.parseLong(roomIdStr);
        String password = servletRequest.getParameter(PASSWORD_KEY);
        try {
            if (rapidChallengeService.checkRoomPassword(roomId, password)) {
                attributes.put(ROOM_ID_KEY, roomId);
                response.getHeaders().add(JwtAuthenticationTokenFilter.WS_TOKEN_HEADER, request.getHeaders().getFirst(JwtAuthenticationTokenFilter.WS_TOKEN_HEADER));
                return true;
            } else {
                response.setStatusCode(HttpStatus.FORBIDDEN);
                log.error("快速挑战大厅>>加入大厅失败 => 房间密码错误: {} > {}", roomId, password);
                return false;
            }
        } catch (IllegalArgumentException e) {
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            log.error("快速挑战大厅>>加入大厅失败 => {}: {} > {}", e.getMessage(), roomId, password);
            return false;
        }
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
